package pers.karl.utils.term.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import pers.karl.utils.term.model.Term;
import pers.karl.utils.term.utils.FileUtils;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Data {

    private String dataFile = "d://temp/data.json";

    private JSONObject data;

    private static ExecutorService executorService = new ThreadPoolExecutor(0, 1,30, TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(10),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    public Data() throws IOException {
        this.data = this.getData();
    }

    /**
     * 获取Json数据
     * @return
     * @throws IOException
     */
    private JSONObject getData() throws IOException {
        String text = FileUtils.readTextFromFile(dataFile);

        return JSON.parseObject(text);
    }

    /**
     * 保存术语(新增 或 更新)
     * @param term
     */
    public void saveTerm(Term term) {
        this.data.put(term.getTitle(), term.getDesc());

        executorService.execute(() -> {
            try{
                FileUtils.writeTextToFile(this.dataFile, data.toJSONString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 获取术语
     * @param title
     * @return
     */
    public Term getTerm(String title) {
        String desc = this.data.getString(title);
        if(desc != null) {
            Term term = new Term();
            term.setTitle(title);
            term.setDesc(desc);
            return term;
        }

        return null;
    }

}
